package com.wgchao.authmanager.infrastructure.repository;

import com.wgchao.authmanager.domain.model.AdminAutho;
import com.wgchao.authmanager.domain.model.AuthoInfo;
import com.wgchao.authmanager.domain.repository.AdminAuthoRepository;
import com.wgchao.authmanager.infrastructure.jpa.entity.UserAuthoHandleInfo;
import com.wgchao.authmanager.infrastructure.jpa.entity.UserAuthoInfo;
import com.wgchao.authmanager.infrastructure.jpa.repository.UserAuthoHandleJpaRepository;
import com.wgchao.authmanager.infrastructure.jpa.repository.UserAuthoInfoJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName: UserAuthoRepositoryImpl
 * @author: wgchao
 * @createTime: 2020/5/9 6:10 PM
 * @Description: TODO
 */
@Component
public class AdminAuthoRepositoryImpl implements AdminAuthoRepository {
    @Autowired
    private UserAuthoInfoJpaRepository uaJpaRepository;
    @Autowired
    private UserAuthoHandleJpaRepository uahJpaRepository;

    @Override
    public void add(AdminAutho adminAutho) {
        //删除原有的授权
        List<UserAuthoInfo> userAuthoInfos = uaJpaRepository.findAllByUname(adminAutho.getUname());
        if(userAuthoInfos != null){
            for(UserAuthoInfo userAuthoInfo : userAuthoInfos){
                List<UserAuthoHandleInfo> userAuthoHandleInfos = uahJpaRepository
                        .findAllByUserAuthoId(userAuthoInfo.getId());
                if(userAuthoHandleInfos!=null && !userAuthoHandleInfos.isEmpty()){
                    uahJpaRepository.deleteAll(userAuthoHandleInfos);
                }
            }
            uaJpaRepository.deleteAll(userAuthoInfos);
            uahJpaRepository.findAll();
            uaJpaRepository.findAll();
        }

        //重新写入授权
        for(AuthoInfo authoInfo : adminAutho.getAuthoInfos()){
            UserAuthoInfo userAuthoInfo = new UserAuthoInfo();
            userAuthoInfo.setUname(adminAutho.getUname());
            userAuthoInfo.setProjectIdentify(authoInfo.getProjectIdentify());
            userAuthoInfo.setMenuIdentify(authoInfo.getMenuIdentify());
            userAuthoInfo.setCreateTime(adminAutho.getOperator().getOperateTime());
            userAuthoInfo.setCreateUser(adminAutho.getOperator().getUname());
            userAuthoInfo = uaJpaRepository.save(userAuthoInfo);

            for(String handle : authoInfo.getHandles()){
                UserAuthoHandleInfo userAuthoHandleInfo = new UserAuthoHandleInfo();
                userAuthoHandleInfo.setHandleIdentify(handle);
                userAuthoHandleInfo.setUserAuthoId(userAuthoInfo.getId());
                userAuthoHandleInfo = uahJpaRepository.save(userAuthoHandleInfo);
            }
        }
    }

    @Override
    public void remove(AdminAutho adminAutho, String operator) {

    }

    @Override
    public AdminAutho get(String id) {
        return null;
    }
}
